package com.wangsd.web.sys.service;

import com.gitee.fastmybatis.core.query.Query;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.common.utils.BaseUtils;
import com.wangsd.web.sys.entity.*;
import com.wangsd.web.sys.mapper.SysRoleMapper;
import com.wangsd.web.sys.mapper.SysUserRoleMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysRoleService {
    @Resource
    SysRoleMapper mapper;
    @Resource
    SysUserRoleMapper userRoleMapper;
    @Autowired
    SysPermissionService permissionService;

    private SysRole selectByName(String name, Long id) {
        Query query = new Query();
        query.eq("name", name);
        if (id != null) {
            query.notEq("id", id);
        }
        return mapper.getByQuery(query);
    }

    public List<SysRole> selectPage(SysRole queryObj) {
        Query query = new Query();
        if (StringUtils.isNotBlank(queryObj.getName())) {
            query.like("name", queryObj.getName());
        }

        List<SysRole> list = mapper.list(query);
        return list;
    }

    /**
     * 根据类型查询所有角色
     * @param type
     * @return
     */
    public List<SysRole> selectRoleByType(Integer type) {
        Query query = new Query();
        query.eq("type", type);
        return mapper.list(query);
    }

    /**
     * 根据用户id查询拥有的角色
     * @param userid
     * @return
     */
    public List<SysRole> selectByUserId(Long userid) {
        Query query = new Query();
        query.join("left join sys_user_role t2 on t.id = t2.role_id")
                .eq("t2.user_id", userid);
        return mapper.list(query);
    }

    @Transactional
    public int saveOrUpdate(SysRole entity) {
        SysRole role = this.selectByName(entity.getName(), entity.getId());
        if (role != null) {
            throw new BusinessException("角色名称不能重复！");
        }

        if (entity.getId() == null) {
            mapper.saveIgnoreNull(entity);
        } else {
            mapper.updateIgnoreNull(entity);
            permissionService.deleteByRoleId(entity.getId());
        }

        //保存权限关系
        List<SysMenu> list = entity.getMenuList();
        List<SysPermission> sysPermissionList = new ArrayList<>();
        List<SysPermission> buttonPermissionList = new ArrayList<>();
        List<SysPermission> menuChildPermissionList = new ArrayList<>();
        for (SysMenu parent : list) {
            //判断孩子有没有保存过
            boolean isSave = false;
            for (SysMenu child : parent.getChildren()) {
                //已配置权限
                if (child.getActions() != null && child.getActions().size() > 0) {
                    isSave = true;
                    List<SysButton> buttonlist = child.getButtonList();
                    for (String action : child.getActions()) {
                        //保存按钮级权限
                        SysPermission button = new SysPermission();
                        button.setRoleId(entity.getId());//角色id
                        button.setAccessType(2);//按钮
                        button.setAccessSign(action);//按钮权限值
                        button.setAccessId(BaseUtils.getButtonId(buttonlist, action));
                        buttonPermissionList.add(button);
                    }
                    //保存2级菜单
                    SysPermission menuChild = new SysPermission();
                    menuChild.setRoleId(entity.getId());//角色id
                    menuChild.setAccessType(1);//菜单
                    menuChild.setAccessId(child.getId());//菜单id
                    menuChild.setAccessSign(child.getKeySign());//菜单权限值
                    menuChildPermissionList.add(menuChild);
                }
            }
            //保存一级菜单
            if (isSave) {
                SysPermission menuParent = new SysPermission();
                menuParent.setRoleId(entity.getId());//角色id
                menuParent.setAccessType(1);//菜单
                menuParent.setAccessId(parent.getId());//菜单id
                menuParent.setAccessSign(parent.getKeySign());//菜单权限值
                sysPermissionList.add(menuParent);
            }
        }

        if (buttonPermissionList.size() > 0) {
            permissionService.saveBatch(buttonPermissionList);
        }
        if (menuChildPermissionList.size() > 0) {
            permissionService.saveBatch(menuChildPermissionList);
        }
        if (sysPermissionList.size() > 0) {
            permissionService.saveBatch(sysPermissionList);
        }
        return 1;
    }

    @Transactional
    public int deleteById(Long id) {
        permissionService.deleteByRoleId(id);
        return mapper.deleteById(id);
    }

    /**
     * 根据用户id删除所有角色
     * @param userId
     * @return
     */
    public int removeRoleByUserId(Long userId) {
        Query query = new Query();
        query.eq("user_id", userId);
        return userRoleMapper.deleteByQuery(query);
    }

    /**
     * 批量保存
     * @param sysUserRoleList
     * @return
     */
    public int saveBatch(List<SysUserRole> sysUserRoleList) {
        return userRoleMapper.saveBatch(sysUserRoleList);
    }
}
